<template>
  <div :class="[prefixCls, 'flex items-center']" v-if="info">
    <Switch
      :loading="loading"
      :checked="newVal"
      @change="handleChange"
      :checkedValue="info.checkedValue"
      :unCheckedValue="info.unCheckedValue"
      :checkedChildren="info.checkedChildren"
      :unCheckedChildren="info.unCheckedChildren"
    />
  </div>
</template>

<script lang="ts" setup name="HSwitch">
  import { ref, computed } from 'vue';
  import { useDesign } from '/@/hooks/web/useDesign';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { Switch } from 'ant-design-vue';
  import { getRowKeys } from '/@/components/ModelTable/src/hooks/functionSet';

  import { commonSwitchApi } from '/@/api/config-center/model-design';

  const { prefixCls } = useDesign('HSwitch');
  const { createMessage } = useMessage();
  const loading = ref(false);
  const props = defineProps<{
    info: Recordable;
    value: any;
  }>();
  const emit = defineEmits<{
    (e: 'change', value: boolean): void;
  }>();

  const newVal = computed({
    get: () => props.value[props.info.dataIndex],
    set: (v) => {
      emit('change', v);
    },
  });

  async function handleChange(e: any) {
    const { moduleId, primaryKey, modelId } = props.info._comParams;
    const dataIndex = props.info.dataIndex;
    const primaryKeys: Indexable = getRowKeys(primaryKey, props.value);
    loading.value = true;
    try {
      await commonSwitchApi(
        { moduleId, modelId },
        {
          [dataIndex]: e,
          ...primaryKeys,
        },
      );
      newVal.value = e;
      createMessage.success('操作成功', 0.7);
    } catch (error) {
    } finally {
      loading.value = false;
    }
  }
</script>
<style lang="less" scoped></style>
